package com.zhihui.util;


import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理后台参数传递工具类
 * Created by star on 2016/10/8.
 */
public class HttpUtils {


    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
     * 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130,
     * 192.168.1.100
     *
     * 用户真实IP为： 192.168.1.110
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }



    // 调用htpp接口
    public static JSONObject httpConnection(String urlStr) throws Exception {
        JSONObject jsonObject = null;
        String res = "";
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url
                    .openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),
                            "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line;
            }
            jsonObject = JSONObject.fromObject(res.toString());
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 获取url传参
     *
     * @param request
     * @param key
     * @return
     */
    public static String getHttpParameter(HttpServletRequest request, String key) {
        String str = request.getParameter(key);
        return str;
    }

    /**
     * 添加session变量
     *
     * @param request
     * @param key
     * @param value
     */
    public static void setSessionAttribute(HttpServletRequest request, String key, Object value) {
        try {
            request.getSession().setAttribute(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取session变量
     *
     * @param request
     * @param key
     * @return
     */
    public static Object getSessionAttribute(HttpServletRequest request, String key) {
        Object obj = request.getSession().getAttribute(key);
        return obj;
    }

    /**
     * 清除session数据
     */
    public static void clear(HttpServletRequest request, String key) {
        request.getSession().removeAttribute(key);
    }


    public static String postWithJson(String strURL, String params) {
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "text/html"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.setRequestProperty("Accept-Encoding", "identity");
            connection.connect();


            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.write(params);
            out.flush();
            out.close();

          /*  ObjectOutputStream oos=new ObjectOutputStream(connection.getOutputStream());
            oos.writeObject(params);
            oos.flush();
            oos.close();*/
            // 读取响应
            int  length=connection.getContentLength();
            InputStream is = connection.getInputStream();


            return  IOUtils.toString(is);

           /* if(length!=-1){


                byte[] data = new byte[length];
                int
                while(is.read()!=-1){

                }

            }*/
            /*String br="";
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
            StringBuffer sb = new StringBuffer();

            while ((br = reader.readLine()) != null)
            {
                sb.append(br).append("\n");
            }

            return sb.toString();
*/
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error"; // 自定义错误信息
    }

    public static void main(String[] args) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new ByteArrayOutputStream());

        Map<String,Object> paraMap=new HashMap<String,Object>();
        paraMap.put("api_type","verify");
        paraMap.put("cert_no","412725199009256534");
        paraMap.put("name","谢恒星");

        String  params= JSONObject.fromObject(paraMap).toString();


//        String result=postWithJson("http://121.196.213.4:701/api/SesameCredit/ZhimaCreditAntifraud",CommonUtils.getBase64(params));
//        String result=postWithJson("http://106.15.120.3:8080/zhsSiteApi/zhima/verify",params);
        String result2=postWithJson("http://localhost:28080/api/lixiang/queryAll",params);
//        String result2=postWithJson("http://localhost:8080/lixiang/queryAll",params);

        //        String result2=postWithJson("http://localhost:28080/api/zhima/verify",params);
        System.out.println("---"+result2);
//        System.out.println(CommonUtils.releaseBase64(result));
    }


    /**
     * 根据request获取参数列表
     * @param params request中的参数列表
     * @return 转换为map<String, String>
     */
    public  static Map<String, String> paramsToMap(Map<String, String[]> params) {
        // 返回的map对象
        Map<String, String> paramMap = new HashMap<String, String>();
        // 遍历request种的参数列表
        for (String key : params.keySet()) {
            String[] values = params.get(key);
            String value = values[0];
            paramMap.put(key, value);
        }
        return paramMap;
    }
}
